﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

using MathTools;

namespace ChartTools
{
    public partial class ChartCanvas : Control
    {
        #region Fields

        LinkedList<double> m_points;

        #endregion
        public ChartCanvas()
        {
        }

        public LinkedList<double> Points
        {
            get
            {
                return m_points;
            }
            set
            {
                m_points = value;
            }
        }

        protected override void OnResize( EventArgs e )
        {
            base.OnResize( e );

            Refresh();
        }

        protected override void OnPaint( PaintEventArgs e )
        {
            const int margin = 25;

            Graphics g = e.Graphics;
            g.Clear( Color.White );

            if( Points == null )
                return;

            double max = double.MinValue;
            double min = double.MaxValue;

            foreach( double d in Points )
            {
                max = d > max ? d : max;
                min = d < min ? d : min;
            }

            double scale = ( e.ClipRectangle.Height - 2 * margin ) / ( max - min );

            g.DrawLine( Pens.Black, new Point( margin, e.ClipRectangle.Height - margin ), new Point( margin, margin ) );
            g.DrawLine( Pens.Black, new Point( margin, e.ClipRectangle.Height - margin ), new Point( e.ClipRectangle.Width - margin, e.ClipRectangle.Height - margin ) );

            g.DrawString( m_points.Count.ToString(), this.Font, Brushes.Blue, new PointF( e.ClipRectangle.Width - margin, e.ClipRectangle.Height - margin - 10 ) );

            g.DrawString( min.ToString(), this.Font, Brushes.Blue, new PointF( margin - 18, e.ClipRectangle.Height - margin + 5 ) );
            g.DrawString( max.ToString(), this.Font, Brushes.Blue, new PointF( margin, margin - 18 ) );

            if( Points.Count > 0 )
            {
                int prev = ( int )( Points.First.Value * scale );
                int i = 0;

                int diff = ( e.ClipRectangle.Width - 2 * margin ) / m_points.Count;

                foreach( double d in Points )
                {
                    i++;

                    if( i == 1 )
                        continue;

                    g.DrawLine( Pens.Green,
                        new Point( diff * ( i - 2 ) + margin, e.ClipRectangle.Height - margin - prev ),
                        new Point( diff * ( i - 1 ) + margin, e.ClipRectangle.Height - margin - ( int )( d * scale ) ) );

                    prev = ( int )( d * scale );
                }
            }
        }

    }
}
